package com.yun.yun

import android.annotation.SuppressLint
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.StrictMode
import android.util.Log
import androidx.core.content.FileProvider
import com.lztek.toolkit.Lztek
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugins.GeneratedPluginRegistrant
import java.io.File


class MainActivity: FlutterActivity() {

    private val lzt = Lztek.create(this)
//    private var idReaderHelper:IdReaderHelper? = null
    private lateinit var toFlutter: MethodChannel

    override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
//        super.configureFlutterEngine(flutterEngine)
        GeneratedPluginRegistrant.registerWith(flutterEngine)
        val android =MethodChannel(flutterEngine.dartExecutor.binaryMessenger,"toAndroid")

        android.setMethodCallHandler { call, result ->
            run {
                if (call.method != null) {
                    if ("hideBar" == call.method) {
                        result.success(hideBar())
                    }
                    if ("showBar" == call.method) {
                        result.success(showBar())
                    }
                    if ("restart" == call.method) {
                        result.success(restart())
                    }
//                    if ("dpm" == call.method) {
//                        result.success(dpm())
//                    }
                    if ("checkScreenOff" == call.method) {
                        result.success(checkScreenOff())
                    }
                    if ("checkScreenOn" == call.method) {
                        result.success(checkScreenOn())
                    }
                    if ("install" == call.method) {
                        result.success(install2(call.argument("message")))
                    }
                    if ("alarm" == call.method) {
                        result.success(alarm(call.argument("onTime"),call.argument("offTime")))
                    }
//                    if ("initVar" == call.method) {
//                        result.success(idReaderHelper!!.initVar(this@MainActivity))
//                    }
                    if ("openDev" == call.method) {
                        result.success(openDev())
                    }
                    if ("closeDev" == call.method) {
                        result.success(closeDev())
                    }
                } else {
                    result.notImplemented()
                }
            }
        }
        toFlutter = MethodChannel(flutterEngine.dartExecutor.binaryMessenger, "toFlutter")

//        idReaderHelper = IdReaderHelper()

    }

    private fun openDev(): String{
        CpuIdReaderHelper.getInstance().openDev(this@MainActivity,readerListener)
//        CpuIdReaderHelper.getInstance().setReaderListener(readerListener)
        return "success"
    }
    private fun closeDev(): String{
        CpuIdReaderHelper.getInstance().closeDev()
//        CpuIdReaderHelper.getInstance().setReaderListener(readerListener)
        return "success"
    }

    private val readerListener: CpuIdReaderHelper.ReaderListener = object :CpuIdReaderHelper.ReaderListener{
        override fun onIdReaderSuccess(data: String?) {
            runOnUiThread {
                toFlutter.invokeMethod("idData", data, object : MethodChannel.Result {

                    override fun success(o: Any?) {

                    }

                    override fun error(s: String, s1: String?, o: Any?) {
                    }

                    override fun notImplemented() {
                    }

                })
            }
        }

        override fun onCpuReaderSuccess(data: String?) {
            runOnUiThread {
                toFlutter.invokeMethod("cpuData", data, object : MethodChannel.Result {

                    override fun success(o: Any?) {

                    }

                    override fun error(s: String, s1: String?, o: Any?) {
                    }

                    override fun notImplemented() {
                    }

                })
            }
        }
    }


//    private fun  initCardReader(): String{
//        idReaderHelper!!.initCardReader(this@MainActivity)
//        return "success"
//    }


    private fun authStart(): String{
        val thisIntent = Intent("com.lztek.tools.action.BOOT_SETUP")
        thisIntent.putExtra(
            "packageName",
            "com.yun.yun"
        )
        thisIntent.putExtra("delaySeconds", 5) // 开机启动完成 5 秒后运行指定 APK

        thisIntent.setPackage("com.lztek.bootmaster.autoboot7") // Android 8.0 or above
        sendBroadcast(thisIntent)
        return "success"
    }

    private fun alarm(onTime:String?,offTime:String?): String{
        Log.v("123123","onTime="+ onTime +"onTime="+offTime)
        val intent = Intent("com.lztek.tools.action.ALARM_DAILY")
        intent.putExtra ("onTime", onTime)
        intent.putExtra("offTime", offTime)
        intent.setPackage("com.lztek.bootmaster.poweralarm7")  // Android 8.0 or above
        context.sendBroadcast(intent)

        return "success"
    }


    private fun hideBar(): String{
        authStart()
        lzt.hideNavigationBar()
        return "success"
    }

    private fun showBar(): String{

        lzt.showNavigationBar()
        return "success"
    }

    private fun restart(): String{
//        mPowerManager = getSystemService(POWER_SERVICE) as PowerManager
//        mPowerManager!!.reboot("")
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
//            deviceAdmin = ComponentName(this, AdminReceiver::class.java)
//
//            dpm!!.reboot(deviceAdmin!!)
//        }
        lzt.softReboot()
        return "success"

    }


    @SuppressLint("InvalidWakeLockTag")
    private fun checkScreenOn(): String {
        lzt.setLcdBackLight(true)
        return "success"
    }

    private fun checkScreenOff(): String {
        lzt.setLcdBackLight(false)
//        dpm!!.lockNow()
        return "success"
    }

    private fun install(path:String?):String{
        lzt.installApplication(path)
        return "success"
    }

    private fun install2(path:String?):String{
        // 创建File对象
        val apkFile: File = File(path)
        // 设置文件Uri访问权限
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            val builder = StrictMode.VmPolicy.Builder()
            StrictMode.setVmPolicy(builder.build())
        }

        // 安装APK
        val intent = Intent(Intent.ACTION_VIEW)
        intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            val apkUri =
                FileProvider.getUriForFile(context, context.packageName + ".fileprovider", apkFile)
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
            intent.putExtra("IMPLUS_INSTALL","SILENT_INSTALL")
            intent.setDataAndType(apkUri, "application/vnd.android.package-archive")
        } else {
            intent.putExtra("IMPLUS_INSTALL","SILENT_INSTALL")
            intent.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive")
        }
        context.startActivity(intent)



//        val intent = Intent(Intent.ACTION_VIEW)
//        intent.setDataAndType(Uri.parse(path),"application/vnd.android.package-archive")
//        intent.putExtra("IMPLUS_INSTALL","SILENT_INSTALL")
//        startActivity(intent)
        return "success"
    }

}
